
<template>
  <el-form
    v-if="form"
    :ref="refName"
    :model="form"
    :size="size"
    :rules="rules"
    :label-suffix="labelSuffix"
    :label-position="labelPosition"
    :label-width="labelWidth"
    @submit.native.prevent
  >
    <el-form-item
      prop="name"
      label="收件人姓名"
      class="form-item--medium"
    >
      <el-input
        ref="formInput.name"
        v-model="form.name"
      />
    </el-form-item>
    <el-form-item
      prop="mobile"
      label="收件人手机号"
      class="form-item--medium"
    >
      <el-input v-model="form.mobile" />
    </el-form-item>
    <el-form-item
      prop="province"
      label="省份"
    >
      <el-cascader
        v-if="showCascader"
        v-model="form.areas"
        placeholder="可按地区名称搜索，例：北京"
        :props="areasProps"
        filterable
        clearable
      />
    </el-form-item>
    <el-form-item
      prop="address_detail"
      label="详细地址"
      class="form-item--medium"
    >
      <el-input v-model="form.address_detail" />
    </el-form-item>
    <el-form-item
      prop="postal_code"
      label="邮编"
      class="form-item--medium"
    >
      <el-input v-model="form.postal_code" />
    </el-form-item>
    <el-form-item
      label="设为默认"
      prop="is_default"
    >
      <el-switch
        v-model="form.is_default"
        :active-value="1"
        :inactive-value="0"
      />
    </el-form-item>
    <el-form-item
      prop="mark"
      label="备注"
      class="form-item--medium"
    >
      <el-input v-model="form.mark" />
    </el-form-item>

    <form-action :fixed="fixed">
      <el-form-item width="300">
        <el-button
          type="primary"
          @click="onSave"
        >{{ submitButtonText }}</el-button>
      </el-form-item>
    </form-action>
  </el-form>
</template>

<script>
import { objectFillMerge } from '@/utils'
import FormAction from '@/components/Form/FormAction'

// var id = 0
export default {
  name: 'AddressForm',
  components: {
    FormAction
  },
  props: {
    primaryKey: {
      type: [String, Number],
      default: ''
    },
    usage: {
      type: String,
      default: ''
    },
    labelPosition: {
      type: String,
      default: ''
    },
    labelWidth: {
      type: String,
      default: '20%'
    },
    labelSuffix: {
      type: String,
      default: ''
    },
    refName: {
      type: String,
      default: 'addressForm'
    },
    size: {
      type: String,
      default: ''
    },
    fixed: {
      type: Boolean,
      default: false
    },
    submitButtonText: {
      type: String,
      default: '提交保存'
    }
  },
  data() {
    return {
      areas: [],
      showCascader: false,
      areasProps: {
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad: (node, resolve) => {
          var pid = node.value || 0
          this.$http.system.region(pid).then(res => {
            resolve(res.data)
          })
        }
      },
      form: {
        name: '',
        mobile: '',
        areas: [],
        address_detail: '',
        postal_code: '',
        mark: '',
        is_default: '',
        usage: ''
      },
      rules: {
        name: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入收件人手机号', trigger: 'blur' }],
        areas: [{ required: true, message: '请选择省市区', trigger: 'change' }],
        address_detail: [{ required: true, message: '请填写详细地址', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.onLoad()
  },
  methods: {
    async lazyLoads(node, resolve) {
      if (node.level === 0) {
        const res = await this.getfristChild() // 不存在就默认加载第一集节点
        resolve(res)
      } else {
        // 有children属性了就不要再请求了,不然字节点会重复
        if (!node.data.children) {
          // 获取子节点数据
          const res = await this.getOther(node.data.value)
          setTimeout(() => {
            resolve(res)
          }, 200)
        } else {
          resolve([])
        }
      }
    },
    // 获取第一层数据
    getProjectList(node, resolve) {
      var pid = node.value || 0
      this.$http.system.region(pid).then(res => {
        resolve(res.data)
      })
    },
    onLoad() {
      console.log('onLoad Form Data')
      this.$http.express.updateAddress(null, this.primaryKey, false).then(res => {
        const { form } = res.data
        console.log('Form Data', form)
        this.form = objectFillMerge(this.form, form)
        this.form.usage = this.usage
        this.showCascader = true
      })
    },
    onSave() {
      this.$refs.addressForm.validate((valid, obj) => {
        if (valid) {
          console.log(this.form)
          this.$http.express.updateAddress(this.form, this.primaryKey).then(res => {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.$emit('saved', res.data)
          })
        } else {
          let firstErrorElname = ''
          for (const i in obj) {
            firstErrorElname = `formInput.${i}`
            break
          }
          var dom = this.$refs[firstErrorElname]
          console.log(dom, this.$refs)
          if (dom) {
            dom.$refs.input && dom.$refs.input.focus()
            dom.$el.scrollIntoView({
              // 滚动到指定节点
              block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
              behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            })
          }
          console.log('error submit!!', this.form)
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" >
.form-item__group {
  display: flex;
  flex-direction: column;
  &.el-form-item > .el-form-item__label {
    border-bottom: 1px solid #f6f6f6;
    float: none;
    margin-bottom: 20px;
    text-align: initial;
  }
  &.el-form-item > .el-form-item__content {
    margin: 0;
    display: flex;
    flex-wrap: wrap;
  }
  &.el-form-item .el-form-item {
    margin-bottom: 22px;
    flex: 50%;
    display: flex;
    flex-direction: column;
    .el-form-item__label {
      float: none;
      text-align: initial;
    }
  }
}
.form-group--small {
  .form-group__content {
    display: grid;
    gap: 10px;
    grid-template-columns: repeat(auto-fill, calc(50% - 10px));
  }
}
</style>
<style lang="scss" scoped>
.deliver-area-table {
  font-size: 12px;
  ::v-deep .el-table__expand-column {
    .el-table__expand-icon {
      .el-icon-arrow-right:before {
        // 这是展开图标
        content: '\e708';
      }
      &--expanded {
        // 这是点击后的旋转角度
        transform: rotate(0);
        .el-icon-arrow-right:before {
          // 这是展开图标
          content: '\e79e';
        }
      }
    }
  }
}
</style>
